package com.lingyun.framework.security;

import com.lingyun.common.vo.LoginUser;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;

/**
 * 自定义身份认证
 * @author 没事别学JAVA
 */
@Component
public class SelfAuthenticationProvider implements AuthenticationProvider {

    @Resource
    private UserDetailsService userDetailsService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        // 获取输入的账号
        String userName = (String) authentication.getPrincipal();

        // 获取输入的密码
        String password = (String) authentication.getCredentials();

        // 根据输入的账号进入数据库中查询
        LoginUser loginUser = (LoginUser) userDetailsService.loadUserByUsername(userName);

        // 判断输入密码和数据库中的是否一致
        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        if (!passwordEncoder.matches(password, loginUser.getLyUser().getPassword())) {// 密码错误
            throw new BadCredentialsException("user.password.not.match");
        }
        return new UsernamePasswordAuthenticationToken(loginUser, loginUser.getPassword(), loginUser.getAuthorities());
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return aClass.equals(UsernamePasswordAuthenticationToken.class);
    }

}
